package dev.zeno.booru;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Base64;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;

public class AddNewActivity extends BaseActivity{

	
	private static final String CUSTOM = "Custom*";
	private static final String GELBOORU = "Gelbooru";
	private static final String DANBOORU = "Danbooru";
	private static final String FAVICON_SERVICE = "http://g.etfv.co/";
	
	TextView nameField, urlField;
	Spinner type;
	Button doneButton;
	ProgressDialog progress;
	int curID = -1;
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_new);
		ActionBar actionBar = getSupportActionBar();
	    actionBar.setDisplayHomeAsUpEnabled(true);
	    nameField = (TextView) findViewById(R.id.nameField);
	    urlField = (TextView) findViewById(R.id.urlField);
	    doneButton = (Button) findViewById(R.id.done);
	    doneButton.setEnabled(false);
	    TextWatcher validator = new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
				if(fieldsAreValid())
					doneButton.setEnabled(true);
				else
					doneButton.setEnabled(false);
			}
		};
	    nameField.addTextChangedListener(validator);
	    urlField.addTextChangedListener(validator);
	    
	    type = (Spinner) findViewById(R.id.type_spinner);
	    List<String> types = new LinkedList<String>();
	    types.add(DANBOORU);
	    types.add(GELBOORU);
	    types.add(CUSTOM);
	    type.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, types));
	    progress = new ProgressDialog(this);
	    progress.setIndeterminate(true);
	}
	
	public void done(View v)
	{
		
		String typeString = type.getSelectedItem().toString();
		int type = -1;
		if(typeString.equals(DANBOORU))
			type = Booru.DANBOORU;
		else if (typeString.equals(GELBOORU))
			type = Booru.GELBOORU;
		else if (typeString.equals(CUSTOM))
			type = Booru.CUSTOMBOORU;
		
		String url = urlField.getText().toString().toLowerCase();
		if(!url.startsWith("http://"))
			url = "http://"+url;
		
		booruDatabase.open();
		curID = (int)booruDatabase.addBooru(nameField.getText().toString(), url, type);
		booruDatabase.close();
		progress.setMessage("Fetching icon...");
		progress.show();
		
		new FaviconDownloadTask().execute(url);
		
	}
	
	public boolean fieldsAreValid()
	{
		return urlField.getText().toString().length() > 0;
	}
	
	class FaviconDownloadTask extends AsyncTask<String, Void, String>
	{

		@Override
		protected String doInBackground(String... params) {
			
			StringBuilder result = new StringBuilder();
			HttpClient client = new DefaultHttpClient();
			for(String url: params)
			{
				HttpGet request = new HttpGet(FAVICON_SERVICE + url);
				try {
					HttpResponse response = client.execute(request);
					InputStream stream = response.getEntity().getContent();
					Bitmap bmp = BitmapFactory.decodeStream(stream);
					ByteArrayOutputStream baos = new ByteArrayOutputStream();
					bmp.compress(Bitmap.CompressFormat.PNG, 100, baos);
					result.append(Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT));
				} catch (ClientProtocolException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			
			return result.toString();
		}
		
		@Override
		protected void onPostExecute(String result)
		{
			booruDatabase.open();
			booruDatabase.setFavicon(curID, result);
			booruDatabase.close();
			progress.dismiss();
			
		}
	}
}
